import 'package:aero_frisbee/app/state/app_cache_state.dart';
import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/core/tools/af_log_manager.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:aero_frisbee/pages/modues/mine/profile/view_model/af_profile_view_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class AfSettingScreen extends ConsumerStatefulWidget {
  const AfSettingScreen({Key? key}) : super(key: key);
  @override
  AfSettingScreenState createState() => AfSettingScreenState();
}

class AfSettingScreenState extends ConsumerState<AfSettingScreen> {
  @override
  Widget build(BuildContext context) {
    ref.listen(deleteAccountServiceProvider, (previousData, newData) {
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        ref.read(appCacheServiceProvider.notifier).logout();
        "delete success".toast(
          onDismiss: () {
            Navigator.of(context).maybePop();
          },
        );
      }
    });
    ref.listen(logoutServiceProvider, (previousData, newData) {
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        ref.read(appCacheServiceProvider.notifier).logout();
        "logout success".toast(
          onDismiss: () {
            Navigator.of(context).maybePop();
          },
        );
      }
    });
    return Scaffold(
      appBar: AppBar(
        leading: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            Navigator.of(context).maybePop();
          },
          child: Align(
            alignment: Alignment.centerLeft,
            child: Padding(
              padding: const EdgeInsets.only(
                left: 20,
              ),
              child: Assets.icons.iconMineBack.image(width: 25),
            ),
          ),
        ),
        title: const Text(
          'Setting',
          style: TextStyle(
            color: Color(0xff404040),
            fontWeight: FontWeight.normal,
            fontSize: 16,
          ),
          textAlign: TextAlign.center,
          overflow: TextOverflow.ellipsis,
          maxLines: 1,
        ),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Column(
          children: [
            const SizedBox(
              height: 45,
            ),
            AfRowItem(
              title: 'Auto Translate',
              isOn: ref.watch(appCacheServiceProvider).maybeWhen(
                    orElse: () => false,
                    data: (data) => data.maybeWhen(
                      orElse: () => false,
                      logined: (loginResposeModel) =>
                          loginResposeModel.autoTranslate,
                    ),
                  ),
              onSwitchChanged: (isOff) {
                ref
                    .read(appCacheServiceProvider.notifier)
                    .toggleAutoTranslate();
              },
            ),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                _showDeleteConfirmationDialog();
              },
              child: AfRowItem(
                title: 'Delete account',
                ondetailsClick: () {},
              ),
            ),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                _showExitConfirmationDialog();
              },
              child: AfRowItem(
                title: 'Logout',
                ondetailsClick: () {},
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _showDeleteConfirmationDialog() async {
    return showCupertinoDialog(
      context: context,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          title: const Text('Confirm Delete'),
          content: const Text(
              'Are you sure you want to delete your account? This action cannot be undone.'),
          actions: [
            CupertinoDialogAction(
              child: const Text('Cancel'),
              onPressed: () {
                Navigator.of(context).pop(); // Close the dialog
              },
            ),
            CupertinoDialogAction(
              child: const Text('Delete'),
              onPressed: () {
                ref.read(deleteAccountServiceProvider.notifier).deleteAccount();
                AFLogPvManger.stat(page: AFLogPages.deleteAccount);
                Navigator.of(context).pop(); // Close the dialog
              },
            ),
          ],
        );
      },
    );
  }

  Future<void> _showExitConfirmationDialog() async {
    return showCupertinoDialog(
      context: context,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          title: const Text('Confirm Exit'),
          content: const Text('Are you sure you want to exit?'),
          actions: [
            CupertinoDialogAction(
              child: const Text('Cancel'),
              onPressed: () {
                Navigator.of(context).pop(); // Close the dialog
              },
            ),
            CupertinoDialogAction(
              child: const Text('Exit'),
              onPressed: () {
                AFLogPvManger.stat(page: AFLogPages.logout);
                ref.read(logoutServiceProvider.notifier).logout();
                Navigator.of(context).pop(); // Close the page
              },
            ),
          ],
        );
      },
    );
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(AfSettingScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}

class AfRowItem extends StatelessWidget {
  const AfRowItem({
    Key? key,
    required this.title,
    this.isOn = false,
    this.onSwitchChanged,
    this.ondetailsClick,
  }) : super(key: key);

  final String title;

  final bool isOn;

  final Function(bool isOff)? onSwitchChanged;
  final Function()? ondetailsClick;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xffF7F8FA),
        borderRadius: BorderRadius.circular(12),
      ),
      margin: const EdgeInsets.symmetric(horizontal: 32, vertical: 10),
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: const TextStyle(
              color: Color(0xff000000),
              fontWeight: FontWeight.normal,
              fontSize: 16,
            ),
            textAlign: TextAlign.left,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          ),
          if (ondetailsClick != null)
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: ondetailsClick,
              child: Assets.icons.iconDetail.image(width: 16),
            ),
          if (onSwitchChanged != null)
            CupertinoSwitch(
              value: isOn,
              onChanged: onSwitchChanged,
            )
        ],
      ),
    );
  }
}
